package org.AftpBrocast;

import java.io.IOException;
import java.net.*;
import java.util.*;

/**
 * AFtpBrocastServerThread is used to brocast the AftpServer's ip and port information
 * @author andy yang buptjunjun@gmail.com
 */
public class AFtpBrocastClientThread extends Thread
{
	private MulticastSocket msocket = null;
	private  String groupIp   = "230.0.0.1";
	private  String ServerIp  = null;
	private     int serverPort  = 3721;
	private     int clientPort = 3722;
	private     int ftpPort    = 0; 
	private     int timeout    = 6000;
	
	public AFtpBrocastClientThread(String groupIp,int clientPort) 
	{
		this.groupIp = groupIp;
		this.clientPort = clientPort;
		
		try 
		{
			//init the socket 
			this.msocket = new MulticastSocket(this.clientPort);
			InetAddress inetaddr = InetAddress.getByName(this.groupIp);
			this.msocket.setSoTimeout(timeout);
			this.msocket.joinGroup(inetaddr);
			
		} 
		catch (Exception e) 
		{

			e.printStackTrace();
		}

	}

    public void run() 
    {
        if(this.msocket == null) return ;
		try
		{
			for(int i = 0; i < 2; i++)
			{
	            
				byte [] buf = new byte[2048];
	            DatagramPacket packet = new DatagramPacket(buf,buf.length);
	            this.msocket.receive(packet);
	            
	            //set the charactor to utf-8
	            buf = packet.getData();
	            String data = new String(buf,"UTF-8").trim();
	            
	            String [] datas = data.split(",");	            
	            this.ServerIp = datas[0];
	            this.ftpPort = Integer.valueOf(datas[1]);
	            System.out.println(getServerIp()+"=="+getFtpPort());
	            System.out.println("client :"+data);
			}
            
		}
		catch (Exception e)
		{ 
			 	this.ServerIp = null;
	            this.ftpPort = 0;
		 	    e.printStackTrace();
		}
		finally{ if(this.msocket!=null) {this.msocket.close(); }}
    }
	public String getServerIp()
	{
		return ServerIp;
	}

	public int getFtpPort() 
	{
		return ftpPort;
	}


    
    public static void main(String [] args)
    {
    	AFtpBrocastClientThread client = new AFtpBrocastClientThread("230.0.0.1",3722);
    	client.start();
    	
    }
	
}
